<?php


namespace app\manage\controller;

use app\manage\model\Admin as AdminModel;
use app\manage\validate\Auth as AuthValidate;
use think\Controller;

class Auth extends Controller
{
    const SESSION_KEY = 'admin_id';

    public function login()
    {
        if (request()->isPost()) {
            $validator = (new AuthValidate());
            $res = $validator->goCheck();
            if (!$res) {
                $this->redirect('/manage/login');
            }
            $username = request()->post('username');
            $password = request()->post('password');
            $password = md5($password);
            $admin = AdminModel::get(function ($query) use ($username, $password) {
                $query->where(['username' => $username, 'password' => $password, 'status' => 1]);
            });

            if (empty($admin)) {
                $this->error('账号或密码不正确, 请重新填写！', '/manage/login');
            }

            session(self::SESSION_KEY, $admin->id);
            $this->redirect('/manage/index/index');
        } else {
            if (!session(self::SESSION_KEY)) {
                session(null);
                return $this->fetch();
            } else {
                $this->redirect('/manage/index/index');
            }
        }
    }

    public function logout()
    {
        session(null);
        $this->redirect('/manage/login');
    }
}